package com.libre.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.libre.auth.entity.LoginLog;
import com.libre.auth.entity.User;
import com.libre.auth.service.LoginLogService;
import com.libre.auth.service.LoginService;
import com.libre.auth.service.UserService;
import com.libre.common.exception.BusinessRuntimeException;
import com.libre.common.utils.JavaWebToken;
import com.libre.common.utils.MD5Util;
import com.libre.common.utils.VerifyUtil;
import com.libre.common.utils.ip.CZIPAddressUtils;
import com.libre.common.utils.ip.IpUtil;
import lombok.extern.slf4j.Slf4j;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    @Value("${jwt.secret-key}")
    public String secretKey;

    @Autowired
    UserService userService;
    @Autowired
    LoginLogService loginLogService;

    @Override
    public JSONObject login(User user, HttpServletRequest request) {
        VerifyUtil.notEmpty("用户名",user.getUsername());
        VerifyUtil.notEmpty("密码",user.getPassword());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("is_delete","0");
        User userInfo = userService.getOne(queryWrapper);
        if (userInfo == null) {
            throw new BusinessRuntimeException("用户不存在");
        } else if (!MD5Util.MD5(user.getPassword() + userInfo.getSalt()).equals(userInfo.getPassword())) {
            throw new BusinessRuntimeException("用户密码错误");
        }
        try{
            /******************** 获取IP以及区域 *******************/
            String ipAddress = IpUtil.getIpAddr(request);
            log.error("IP ======================================== " + ipAddress);
            CZIPAddressUtils ip = new CZIPAddressUtils();
            ip.init();
            System.out.println("IP地址[" + ipAddress + "]获取到的区域信息:" + ip.getIPLocation(ipAddress).getCountry() + ", 获取到的城市:" + ip.getIPLocation(ipAddress).getCity() + ", 运营商:" + ip.getIPLocation(ipAddress).getArea());

            /******************** 获取浏览器信息 *******************/
            //获取浏览器信息
            String ua = request.getHeader("User-Agent");
            //转成UserAgent对象
            UserAgent userAgent = UserAgent.parseUserAgentString(ua);
            //获取浏览器信息
            Browser browser = userAgent.getBrowser();
            //获取系统信息
            OperatingSystem os = userAgent.getOperatingSystem();
            //系统名称
            String system = os.getName();
            //浏览器名称
            String browserName = browser.getName();
            log.info("系统名称:"+system);
            log.info("浏览器名称:"+browserName);
            LoginLog loginLog = new LoginLog();
            loginLog.setUsername(user.getUsername());
            loginLog.setIp(ipAddress);
            loginLog.setArea(ip.getIPLocation(ipAddress).getCountry());
            loginLog.setCity(ip.getIPLocation(ipAddress).getCity());
            loginLog.setOperator(ip.getIPLocation(ipAddress).getArea());
            loginLog.setSystem(system);
            loginLog.setBrowser(browserName);
            loginLog.setLoginTime(new Date());
            loginLogService.save(loginLog);

        }catch (Exception e){
            log.error("获取用户信息异常：",e);
        }

        String accessToken = JavaWebToken.createJWT(user.getUsername(), user.getPassword(), secretKey, 300 * 60 * 1000);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", userInfo);
        jsonObject.put("accessToken", accessToken);
        return jsonObject;
    }

    @Override
    public void logout(User user, HttpServletRequest request) {

    }
}
